package com.sixstones.fragment.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sixstones.fragment.dao.CatagoryDao;
import com.sixstones.fragment.dao.FragmentDao;
import com.sixstones.fragment.entity.CatagoryEntity;
import com.sixstones.fragment.entity.FragmentEntity;
import com.sixstones.fragment.enums.ResultEnum;
import com.sixstones.fragment.service.CatagoryService;
import com.sixstones.fragment.vo.CatagoryInfo;
import com.sixstones.fragment.vo.FragmentException;

@Service
public class CatagoryServiceImpl implements CatagoryService {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private CatagoryDao dao;

	@Autowired
	private FragmentDao fragmentDao;

	@Override
	@Transactional
	public int addCatagory(String name, String desc) throws FragmentException {
		try {
			CatagoryEntity catagory = dao.queryByName(name);
			if (catagory != null) {
				throw new FragmentException(ResultEnum.CATAGORY_REPEAT.toString());
			}
			return dao.addCatagory(name, desc);
		} catch (Exception e) {
			logger.error("新增种类异常", e);
			throw new FragmentException(e.getMessage());
		}
	}

	@Override
	public List<CatagoryEntity> queryAll() {
		return dao.queryAll();
	}

	@Override
	public CatagoryInfo getCatagoryInfo(int CatagoryId,boolean queryFragments) {
		CatagoryInfo catagory = new CatagoryInfo();
		try {
			CatagoryEntity entity = dao.queryById(CatagoryId);
			if (entity == null) {
				logger.error("该种类不存在，catagoryId = {}", CatagoryId);
				return null;
			} else {
				catagory.setCatagory(entity);
				if(queryFragments){
					List<FragmentEntity> fragments = fragmentDao.queryByCatagoryId(CatagoryId);
					catagory.setFragments(fragments);
				}
				return catagory;
			}
		} catch (Exception e) {
			logger.error("异常{}", e);
			return null;
		}
	}

}
